use rbatis::Error;
use rbs::Value;

use crate::{
    config::AppContext,
    domain::{class::Class, topic::Topic},
};

pub async fn save(class: &mut Class) -> Result<u64, Error> {
    let rb = AppContext::rbatis();
    if class.ord.unwrap_or_default() == 0 {
        class.ord = None;
    }
    if class.id.unwrap_or_default() == 0 {
        class.id = None;
        let exec_result = Class::insert(rb, class).await?;
        match exec_result.last_insert_id {
            Value::U64(id) => Ok(id),
            _ => Err(Error::E(String::from("error"))),
        }
    } else {
        Class::update_by_column_skip(rb, class, "id", true).await?;
        Ok(class.id.unwrap())
    }
}

pub async fn delete(class: &Class) -> Result<(), Error> {
    let rb = AppContext::rbatis().acquire_begin().await.unwrap();
    let mut tx = rb.defer_async(|mut tx| async move {
        if !tx.done {
            let _ = tx.rollback().await;
        }
    });
    let _ = Class::delete_by_column(&tx, "id", class.id).await.unwrap();
    Topic::clear_by_tid(&tx, &Topic::default(), class.id.unwrap()).await?;
    let _ = tx.commit().await;
    Ok(())
}
